

from jplur.player import Player
import pickle
import time

def login(self, line): #self is the protocol object
	splitline = line.lower().split(" ")
	
	if self.status == 0: #was asked for name
		safeName = line
		
		if len(safeName) <= 2 or len(safeName) >= 12:
			self.Send({"action": "message", "data": "must be 3 to 12 characters, try again:"})
			
		
			
		elif safeName.lower() in ['look', 'get', 'kill', 'kil','loo', 'who', 'help']:
				self.Send({"action": "message", "data": "illegal name, try again:"})
				
				
		else:
			self.name = safeName
			
			for entry in self._server.players: #allready logged in?
				if safeName == entry.name and entry.logged == 1:
					self.player = entry #go ahead and assume that player, the check for password is below
					self.Send({"action": "message", "data": "Enter your password (re-login):"})
					
					self.dopple = 1
					self.status = 1
	
			if self.dopple == 0:
				
				#make sure player isn't allready loaded
				#try to load character
				
				try:
					savefile = open('./players/'+self.name+'.sav', 'r') #load player object
					self.player = pickle.load(savefile)
					self.player.protocol = self
					
					self.player.time = time.time()
					self.player.idletime = time.time()
					
					savefile.close()
					self.Send({"action": "message", "data": "What is your password?"})
					
					self.status = 1
				except:
					self.new = 1
					self.Send({"action": "message", "data": "NEW CHARACTER: What is your password?"})
					
					self.status = 1
				
		
	elif self.status == 1: #was asked for password
		safePass = line
		
		if self.dopple == 1:
			if self.player.password == safePass:
				# delete other protocol and player reference, tell player object this is its protocol
				self.status = 2
				self.Send({"action": "message", "data": "Login successful!"})
				self.player.protocol = self
				for entry in self._server.players:
					if entry.player == self.player and entry != self:
						del self._server.clientProtocols[ self._server.players.index(entry) ]          
				
		elif self.new == 0: #not new
			if self.player.password == safePass:
				self.status = 2
				
				self.sendLine("Login successful!")
			else:
				self.sendLine(color("red")+"Incorrect password."+color("white"))
				self.status = 0
				self.sendLine("Enter your name:")
				
				del self.player
				
		elif len( safePass ) > 2: #making a new password #new == 1
			self.player = Player(self) #wonky, self is the channel
			self.player.password = safePass
			self.player.name = self.name
			self.status = 3
		else:
			self.sendLine("Too short, try again:")
			

			
	if self.status == 2: #Skipping status 3 for creation
		if self.new == 0:
			self.status = 4
		
